package com.diyunapp.xilinapp.base;

/**
* 
* 上传工具类
* 支持上传文件和参数
*/

import android.util.Log;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

public class UploadUtil {

	private static UploadUtil uploadUtil;
	private static final String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
	private static final String PREFIX = "--";
	private static final String LINE_END = "\r\n";
	private static final String CONTENT_TYPE = "multipart/form-data"; // 内容类型
	private UploadUtil() {

	}

	/**
	* 单例模式获取上传工具类
	* @return
	*/
	public static UploadUtil getInstance() {
		if (null == uploadUtil) {
			uploadUtil = new UploadUtil();
		}
		return uploadUtil;
	}

	private static final String TAG = "UploadUtil";
	private int readTimeOut = 10 * 1000; // 读取超时
	private int connectTimeout = 10 * 1000; // 超时时间
	/***
	* 请求使用多长时间
	*/
	private static int requestTime = 0;

	private static final String CHARSET = "utf-8"; // 设置编码

	/***
	* 上传成功
	*/
	public static final int UPLOAD_SUCCESS_CODE = 0;
	/**
	* 文件不存在
	*/
	public static final int UPLOAD_FILE_NOT_EXISTS_CODE = 2;
	/**
	* 服务器出错
	*/
	public static final int UPLOAD_SERVER_ERROR_CODE = 3;
	protected static final int WHAT_TO_UPLOAD = 1;
	protected static final int WHAT_UPLOAD_DONE = 2;

	/**
	* android上传文件到服务器
	*
//	* @param filePath
//	* 需要上传的文件的路径
//	* @param fileKey
//	* 在网页上<input type=file name=xxx/> xxx就是这里的fileKey
	* @param RequestURL
	* 请求的URL
	*/
	public void uploadFile(final String filePath1,final String filePath2, final String RequestURL,final Map<String, String> params) {
		if (filePath1 == null ||filePath2 == null) {
			sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在");
			return;
		}
		try {
			Log.i(TAG, "请求的URL=" + RequestURL);
			File file1 = new File(filePath1);
			File file2 = new File(filePath2);
			Log.i(TAG, "请求的fileName1=" + file1.getName()+"；请求的fileName2=" + file2.getName());
			new Thread(new Runnable() { //开启线程上传文件
					@Override
					public void run() {
						toUploadFile(filePath1, filePath2,RequestURL,params);
					}
				}).start();
		} 
		catch (Exception e) {
			sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在");
			e.printStackTrace();
			return;
		}
	}
	//==================
	public void uploadFile(final String filePath1,final String filePath2, final String filePath3, final String RequestURL,final Map<String, String> params) {
		if (filePath1 == null ||filePath2 == null) {
			sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在");
			return;
		}
		try {
			Log.i(TAG, "请求的URL=" + RequestURL);
			File file1 = new File(filePath1);
			File file2 = new File(filePath2);
			Log.i(TAG, "请求的fileName1=" + file1.getName()+"；请求的fileName2=" + file2.getName());
			new Thread(new Runnable() { //开启线程上传文件
				@Override
				public void run() {
					toUploadFile(filePath1, filePath2,filePath3,RequestURL,params);
				}
			}).start();
		}
		catch (Exception e) {
			sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在");
			e.printStackTrace();
			return;
		}
	}
	//================
	public void uploadFile(final String filePath, final String RequestURL,final Map<String, String> params) {
		if (filePath == null ) {
			sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在");
			return;
		}
		try {
			Log.i(TAG, "请求的URL=" + RequestURL);
			File file = new File(filePath);
			//File file2 = new File(filePath2);
			//Log.i(TAG, "请求的fileName1=" + file1.getName()+"；请求的fileName2=" + file2.getName());
			new Thread(new Runnable() { //开启线程上传文件
					@Override
					public void run() {
						toUploadFile(filePath,RequestURL,params);
					}
				}).start();
		} 
		catch (Exception e) {
			sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在");
			e.printStackTrace();
			return;
		}
	}
	
  /* 上传文件至Server，uploadUrl：接收文件的处理页面 */
  private void toUploadFile(String srcPath1,String srcPath2,String RequestURL,Map<String, String> params)
  {
    String end = "\r\n";
    String twoHyphens = "--";
    String boundary = "******";
    try
    {
      URL url = new URL(RequestURL);
      HttpURLConnection httpURLConnection = (HttpURLConnection) url
          .openConnection();
      // 设置每次传输的流大小，可以有效防止手机因为内存不足崩溃
      // 此方法用于在预先不知道内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。
      //httpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K
      // 允许输入输出流
      httpURLConnection.setDoInput(true);
      httpURLConnection.setDoOutput(true);
      httpURLConnection.setUseCaches(false);
      // 使用POST方法
      httpURLConnection.setRequestMethod("POST");
      //httpURLConnection.setRequestProperty("Content-Type", "text/html");
      httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
      //httpURLConnection.setRequestProperty("charset", HTTP.UTF_8);
      httpURLConnection.setRequestProperty("Charset", "lwrh0530");
      httpURLConnection.setRequestProperty("Content-Type",
          "multipart/form-data;boundary=" + boundary);
      
      //上传第一张图片
      DataOutputStream dos = new DataOutputStream(
          httpURLConnection.getOutputStream());
      dos.writeBytes(twoHyphens + boundary + end);
      dos.writeBytes("Content-Disposition: form-data; name=\"refund_pic1\"; filename=\""
          + srcPath1.substring(srcPath1.lastIndexOf("/") + 1)
          + "\""
          + end);
      dos.writeBytes(end);

      FileInputStream fis = new FileInputStream(srcPath1);
      byte[] buffer = new byte[8192]; // 8k
      int count = 0;
      // 读取文件
      while ((count = fis.read(buffer)) != -1)
      {
        dos.write(buffer, 0, count);
      }
      fis.close();

      dos.writeBytes(end);
      dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
      
      //上传第二张图片
      dos.writeBytes(twoHyphens + boundary + end);
      dos.writeBytes("Content-Disposition: form-data; name=\"refund_pic2\"; filename=\""
          + srcPath2.substring(srcPath2.lastIndexOf("/") + 1)
          + "\""
          + end);
      dos.writeBytes(end);
      FileInputStream fis2 = new FileInputStream(srcPath2);
      byte[] buffer2 = new byte[8192]; // 8k
      int count2 = 0;
      // 读取文件
      while ((count2 = fis2.read(buffer2)) != -1)
      {
        dos.write(buffer2, 0, count2);
      }
      fis2.close();

      dos.writeBytes(end);
      
      Set<String> keySet = params.keySet();
      for (Iterator<String> it = keySet.iterator(); it.hasNext();)
      {
		  String name = it.next();
		  String value = params.get(name);
		  dos.writeBytes(twoHyphens + boundary + end);
		  dos.writeBytes("Content-Disposition: form-data; name=\"" + name +"\""+ end);
		  dos.writeBytes("Content-Type: text/html; charset="   + CHARSET + LINE_END);
		  dos.writeBytes(end);
		  //dos.writeBytes(value + end);
		  dos.writeBytes(URLEncoder.encode(value, "UTF-8")+ end);
      }
	  
      dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
      dos.flush();
      Log.i("info", dos.toString());
      InputStream is = httpURLConnection.getInputStream();
      InputStreamReader isr = new InputStreamReader(is, "utf-8");
      BufferedReader br = new BufferedReader(isr);
      String result = br.readLine();

      Log.i("zhangxiaoxidebug", result);
      dos.close();
      is.close();
      JSONObject upresult = new JSONObject(result);
      if(upresult.getInt("code")==200)
      {
    	  Log.i("zhangxiaoxidebug", "resultcode ok");
    	  sendMessage(UPLOAD_SUCCESS_CODE, "上传成功");
      }
      else
      {
    	  Log.i("zhangxiaoxidebug", "resultcode fail");
    	  sendMessage(UPLOAD_SERVER_ERROR_CODE, upresult.getString("data"));
      }
    } catch (Exception e){
    	Log.i("zhangxiaoxidebug", "Exception");
    	sendMessage(UPLOAD_SERVER_ERROR_CODE, "上传失败！");
      e.printStackTrace();
    }
  }
	/* 上传文件至Server，uploadUrl：接收文件的处理页面 */
	private void toUploadFile(String srcPath1,String srcPath2,String srcPath3,String RequestURL,Map<String, String> params)
	{
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "******";
		try
		{
			URL url = new URL(RequestURL);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url
					.openConnection();
			// 设置每次传输的流大小，可以有效防止手机因为内存不足崩溃
			// 此方法用于在预先不知道内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。
			//httpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K
			// 允许输入输出流
			httpURLConnection.setDoInput(true);
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setUseCaches(false);
			// 使用POST方法
			httpURLConnection.setRequestMethod("POST");
			//httpURLConnection.setRequestProperty("Content-Type", "text/html");
			httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
			//httpURLConnection.setRequestProperty("charset", HTTP.UTF_8);
			httpURLConnection.setRequestProperty("Charset", "lwrh0530");
			httpURLConnection.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);

			//上传第一张图片
			DataOutputStream dos = new DataOutputStream(
					httpURLConnection.getOutputStream());
			dos.writeBytes(twoHyphens + boundary + end);
			dos.writeBytes("Content-Disposition: form-data; name=\"refund_pic1\"; filename=\""
					+ srcPath1.substring(srcPath1.lastIndexOf("/") + 1)
					+ "\""
					+ end);
			dos.writeBytes(end);

			FileInputStream fis = new FileInputStream(srcPath1);
			byte[] buffer = new byte[8192]; // 8k
			int count = 0;
			// 读取文件
			while ((count = fis.read(buffer)) != -1)
			{
				dos.write(buffer, 0, count);
			}
			fis.close();

			dos.writeBytes(end);
			dos.writeBytes(twoHyphens + boundary + twoHyphens + end);

			//上传第二张图片
			dos.writeBytes(twoHyphens + boundary + end);
			dos.writeBytes("Content-Disposition: form-data; name=\"refund_pic2\"; filename=\""
					+ srcPath2.substring(srcPath2.lastIndexOf("/") + 1)
					+ "\""
					+ end);
			dos.writeBytes(end);
			FileInputStream fis2 = new FileInputStream(srcPath2);
			byte[] buffer2 = new byte[8192]; // 8k
			int count2 = 0;
			// 读取文件
			while ((count2 = fis2.read(buffer2)) != -1)
			{
				dos.write(buffer2, 0, count2);
			}
			fis2.close();

			dos.writeBytes(end);
			dos.writeBytes(twoHyphens + boundary + twoHyphens + end);

			//上传第san张图片
			dos.writeBytes(twoHyphens + boundary + end);
			dos.writeBytes("Content-Disposition: form-data; name=\"refund_pic3\"; filename=\""
					+ srcPath3.substring(srcPath3.lastIndexOf("/") + 1)
					+ "\""
					+ end);
			dos.writeBytes(end);
			FileInputStream fis3 = new FileInputStream(srcPath3);
			byte[] buffer3 = new byte[8192]; // 8k
			int count3 = 0;
			// 读取文件
			while ((count3 = fis3.read(buffer3)) != -1)
			{
				dos.write(buffer3, 0, count3);
			}
			fis3.close();

			dos.writeBytes(end);

			Set<String> keySet = params.keySet();
			for (Iterator<String> it = keySet.iterator(); it.hasNext();)
			{
				String name = it.next();
				String value = params.get(name);
				dos.writeBytes(twoHyphens + boundary + end);
				dos.writeBytes("Content-Disposition: form-data; name=\"" + name +"\""+ end);
				dos.writeBytes("Content-Type: text/html; charset="   + CHARSET + LINE_END);
				dos.writeBytes(end);
				//dos.writeBytes(value + end);
				dos.writeBytes(URLEncoder.encode(value, "UTF-8")+ end);
			}

			dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
			dos.flush();
			Log.i("info", dos.toString());
			InputStream is = httpURLConnection.getInputStream();
			InputStreamReader isr = new InputStreamReader(is, "utf-8");
			BufferedReader br = new BufferedReader(isr);
			String result = br.readLine();

			Log.i("zhangxiaoxidebug", result);
			dos.close();
			is.close();
			JSONObject upresult = new JSONObject(result);
			if(upresult.getInt("code")==200)
			{
				Log.i("zhangxiaoxidebug", "resultcode ok");
				sendMessage(UPLOAD_SUCCESS_CODE, "上传成功");
			}
			else
			{
				Log.i("zhangxiaoxidebug", "resultcode fail");
				sendMessage(UPLOAD_SERVER_ERROR_CODE, upresult.getString("data"));
			}
		} catch (Exception e){
			Log.i("zhangxiaoxidebug", "Exception");
			sendMessage(UPLOAD_SERVER_ERROR_CODE, "上传失败！");
			e.printStackTrace();
		}
	}
  private void toUploadFile(String srcPath,String RequestURL,Map<String, String> params)
  {
    String end = "\r\n";
    String twoHyphens = "--";
    String boundary = "******";
    try
    {
      URL url = new URL(RequestURL);
      HttpURLConnection httpURLConnection = (HttpURLConnection) url
          .openConnection();
      // 设置每次传输的流大小，可以有效防止手机因为内存不足崩溃
      // 此方法用于在预先不知道内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。
      //httpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K
      // 允许输入输出流
      httpURLConnection.setDoInput(true);
      httpURLConnection.setDoOutput(true);
      httpURLConnection.setUseCaches(false);
      // 使用POST方法
      httpURLConnection.setRequestMethod("POST");
      //httpURLConnection.setRequestProperty("Content-Type", "text/html");
      httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
      //httpURLConnection.setRequestProperty("charset", HTTP.UTF_8);
      httpURLConnection.setRequestProperty("Charset", "lwrh0530");
      httpURLConnection.setRequestProperty("Content-Type",
          "multipart/form-data;boundary=" + boundary);
      
      //上传第一张图片
      DataOutputStream dos = new DataOutputStream(
          httpURLConnection.getOutputStream());
      dos.writeBytes(twoHyphens + boundary + end);
      dos.writeBytes("Content-Disposition: form-data; name=\"refund_pic1\"; filename=\""
          + srcPath.substring(srcPath.lastIndexOf("/") + 1)
          + "\""
          + end);
      dos.writeBytes(end);

      FileInputStream fis = new FileInputStream(srcPath);
      byte[] buffer = new byte[8192]; // 8k
      int count = 0;
      // 读取文件
      while ((count = fis.read(buffer)) != -1)
      {
        dos.write(buffer, 0, count);
      }
      fis.close();

      dos.writeBytes(end);
     // dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
      
      /*//上传第二张图片
      dos.writeBytes(twoHyphens + boundary + end);
      dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile2\"; filename=\""
          + srcPath2.substring(srcPath2.lastIndexOf("/") + 1)
          + "\""
          + end);
      dos.writeBytes(end);
      FileInputStream fis2 = new FileInputStream(srcPath2);
      byte[] buffer2 = new byte[8192]; // 8k
      int count2 = 0;
      // 读取文件
      while ((count2 = fis2.read(buffer2)) != -1)
      {
        dos.write(buffer2, 0, count2);
      }
      fis2.close();

      dos.writeBytes(end);*/
      
      Set<String> keySet = params.keySet();
      for (Iterator<String> it = keySet.iterator(); it.hasNext();)
      {
		  String name = it.next();
		  String value = params.get(name);
		  dos.writeBytes(twoHyphens + boundary + end);
		  dos.writeBytes("Content-Disposition: form-data; name=\"" + name +"\""+ end);
		  dos.writeBytes("Content-Type: text/html; charset="   + CHARSET + LINE_END);
		  dos.writeBytes(end);
		  dos.writeBytes(value + end);
		  //dos.writeBytes(URLEncoder.encode(value, "UTF-8")+ end);
      }
	  
      dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
      dos.flush();
      Log.i("info", "dos.toString()="+dos.toString());
      InputStream is = httpURLConnection.getInputStream();
      InputStreamReader isr = new InputStreamReader(is, "utf-8");
      BufferedReader br = new BufferedReader(isr);
      String result = br.readLine();

      Log.i("info", "result="+result);
      dos.close();
      is.close();
      JSONObject upresult = new JSONObject(result);
      String uplodeString = upresult.getString("data");
      if(upresult.getInt("code")==200)
      {
    	  Log.i("info", "resultcode ok");
    	  sendMessage(UPLOAD_SUCCESS_CODE, uplodeString);
      }
      else
      {
    	  Log.i("info", "resultcode fail");
    	  sendMessage(UPLOAD_SERVER_ERROR_CODE, upresult.getString("data"));
      }
    } catch (Exception e){
    	Log.i("info", "Exception");
    	sendMessage(UPLOAD_SERVER_ERROR_CODE, "上传失败！");
      e.printStackTrace();
    }
  }
	
	/**
	* 发送上传结果
	* @param responseCode
	* @param responseMessage
	*/
	private void sendMessage(int responseCode,String responseMessage)
	{
		onUploadProcessListener.onUploadDone(responseCode, responseMessage);
	}

	/**
	* 下面是一个自定义的回调函数，用到回调上传文件是否完成
	* 
	* 
	*/
	public static interface OnUploadProcessListener {
		/**
		* 上传响应
		* @param responseCode
		* @param message
		*/
		void onUploadDone(int responseCode, String message);
		/**
		* 上传中
		* @param uploadSize
		*/
		void onUploadProcess(int uploadSize);
		/**
		* 准备上传
		* @param fileSize
		*/
		void initUpload(int fileSize);
	}
	
	private OnUploadProcessListener onUploadProcessListener;

	public void setOnUploadProcessListener(
			OnUploadProcessListener onUploadProcessListener) {
		this.onUploadProcessListener = onUploadProcessListener;
	}

	public int getReadTimeOut() {
		return readTimeOut;
	}

	public void setReadTimeOut(int readTimeOut) {
		this.readTimeOut = readTimeOut;
	}

	public int getConnectTimeout() {
		return connectTimeout;
	}

	public void setConnectTimeout(int connectTimeout) {
		this.connectTimeout = connectTimeout;
	}
	/**
	* 获取上传使用的时间
	* @return
	*/
	public static int getRequestTime() {
		return requestTime;
	}

	public static interface uploadProcessListener{

	}
}
